
import { ElMessage } from 'element-plus'
import server from '@/api/user';
import comServer from '@/api/pages';
import auth from '@/router/auth';
import {api} from '@/api/api';
import { initSiteData, saveDealSiteData} from "@/store/components-utils";
import { EVENT_HOVER_TYPES } from "@/common/events";
import { H5_TYPE } from '@/common/const-dif';

export let loginBlockAPI = {}

// initial state
const state = {
  user: {
    user: {
      group: -1
    }
  },
  mediaAllData: {},
  siteTempPreviewItem: null,
  siteData: {},
  siteDatas: {},
  sitePreview: {
    isActive: false,  // show / hide
    id: '',  // site_id
    isEditSite: true,  // 是否编辑时 即 h5edit/cardedit
  },

  // admin
  myLists: [],
  myListsData: {},
  myNavPrev: {},
  mySite4Data: {},
  detailNavPrev: {},
  exportData: {
    site_id: -1,
    total: 0,
    data: '',
  },
  clickStatics: {},
  isDisplayClickStatics: false,
  formDataTable: {},
  myPopularize: {  // 推广数据
    popularMarkData: {},
    popularDayData: {},
  },
  tagAddList: [],
}
// getters
const getters = {
  isLottery(){
    let pages = state.siteData && state.siteData.pages
    if(!pages || pages.length < 0){
      return false
    }
    let pageLen = pages.length
    let page
    let components
    let isLottery = false
    for(let i = 0; i < pageLen; i++){
      page = pages[i]
      components = page.components
      let componentData
      for(let j = 0, len = components.length; j < len; j++){
        componentData = components[j]
        let events = componentData.events
        if(events[EVENT_HOVER_TYPES.lottery.type]){
          isLottery = true
          break
        }
      }
    }
    return isLottery
  }
}

// actions
const actions = {
  updateClickStatics({commit}, params){
    let callback =  params.callback
    delete params.callback
    server.getClickStatics(params, function(data){
      commit('updateClickStatics', data);
      if (callback) callback();
    })
  },
  updateOtherSettingShare: ({commit}, data) => {
    commit('updateOtherSettingShare', data);
  },
  saveImgToServer: (store, params) => {
    let {commit, rootState} = store;
    params.site_id = rootState.components.id;
    const fileType = params.fileType
    delete params.fileType;
    server.saveImgToServer(params,function(){
      let params_ = { page:1, pageSize:20, type: fileType }
      server.getMediaData(params_, function(data){
        let data_ = {}
        data_[params_.type] = data
        data_[params_.type].isResetList = true
        commit('setMediaData', data_);
      });
    })
  },
  initUserInfo({commit}){
    commit('setUserInfo', auth.getUserInfo());
  },
  saveSiteData(store, id){
    let { state } = store;
    let data = state.siteDatas[id];
    // data.attrs.share = _.clone(rootState.components.attrs.share);
    comServer.savePageDatas(saveDealSiteData(data.controls, data), function() {
      // commit('saveSiteData');
    })
  },
  // getUserId: (store) => {
  //   let { rootState } = store;
  //   let params = {siteid:rootState.components.id};
  //   server.getUserId(params,function(){
  //     auth.login();
  //   })
  // },
  login: ({commit}, params) => {
    server.login({
      phone: params.phone,
      vcode: params.vcode,
      code: params.code,
    }, function(data){
      if(900003 == data.code) {
        ElMessage(data.msg);
        return;
      }
      if(910007 == data.code) {
        ElMessage(data.msg);
        return;
      }
      if(910008 == data.code) {
        ElMessage(data.msg);
        params.callback(data);
        return;
      }
      params.callback(data);
      auth.login();
      for(let key in loginBlockAPI){
        api.post(key, loginBlockAPI[key].params, loginBlockAPI[key].cb)
        delete loginBlockAPI[key]
      }
      server.getUserInfo(null, function(data){
        auth.setUserInfo(data);
        commit('setUserInfo', data);
      })
    });
  },

  logout: ({commit}, params) => {
    server.logout(params, function(data) {
      auth.logout();
      auth.setUserInfo({});
      commit('setUserInfo', {});
      let siteList = {}
      commit('setMyLists', {siteList});

      // 退出登录提示/跳转
      setTimeout(function() {
        eval(data.match(/^<script>(.*)<\/script>$/)[1]);
      }, 100);
    });
  },
  resetPassword: ({dispatch, commit}, params) => {
    server.resetPassword(params, function(data) {
      if (0 == data.code) {
        // calback
        if(params.callback) params.callback(data);

        // 退出登录
        let link = '#/';
        dispatch('logout', {jumpLink: encodeURIComponent(link)});
      }
      else if(params.callback) params.callback(data);
    });
  },
  getMediaData({commit}, params){
    let cb = params.callback;
    delete params.callback
    server.getMediaData(params, function(data){
      let data_ = {}
      data_[params.type] = data
      if(params.isResetList){
        data_[params.type].isResetList = true;
      }
      commit('setMediaData', data_);
      if(cb){
        cb()
      }
    });
  },
  deleteMediaList({commit}, params){
    commit('deleteMediaList', params);
    if(params.items.length > 0){
      server.deleteMediaList({ids: params.items.toString()}, function(data){
        console.log("删除 media item" + data);
      });
    }
  },
  addMediaItem({commit}, params){
    commit('addMediaItem', params);
  },
  updateMediaItem({commit}, params){
    commit('updateMediaItem', params);
  },
  getMyLists(store, params){
    let {commit, rootState} = store;
    // if(state.myLists.length <= 0){
      server.getMyLists(params, function(data){
        commit('setMyLists', data);
        commit('setMyListsData', data);

        // if callback
        if(params.callback) params.callback();
      })
    // }
    if(!rootState.components.fileUploadData){
      setTimeout(function(){
        comServer.getFileUploadData((data) => {
          commit("components/setFileUploadData", data, {root:true});
        }, 1000);
      })
    }
  },
  getSiteData(store, {item, callback, isTempPreviewUrl}){
    let {commit, state, rootState} = store;
    if(!state.siteDatas[item.site_id]){
      server.getSiteData({id:item.site_id}, (data) => {
        dealSiteData(data);
      });
    }else{
      let data = state.siteDatas[item.site_id];
      dealSiteData(data);
    }
    function dealSiteData(data_){
      if(callback){
        callback(data_);
      }else{
        let isEditSite = false;
        let siteStatus = rootState.components.siteStatus;
        let componentFrontAttr = rootState.components.componentFrontAttr;
        let fileUploadData = rootState.components.fileUploadData;
        if (data_.attrs && data_.attrs.h5Type != H5_TYPE.card) {
          commit('setSiteData', initSiteData(data_, isEditSite, siteStatus, componentFrontAttr, fileUploadData));
        }
        if(isTempPreviewUrl){
          server.getTempPreviewUrl({ site_id: item.site_id }, function (data) {
            commit('setSitePreview', {isActive: true});
            commit("setTempPreviewUrl", data)
          })
        }
      }
    }

    //设置将preview站点的share数据设置到store中的share中，以便在组件中操作后更新数据
    // rootState.components.attrs.share = state.siteData.attrs.share;
  },
  setSitePreview({commit}, params){
    commit('setSitePreview', params);
  },
  async onlineSite({commit}, params) {
    let isTempPreviewUrl = params.isTempPreviewUrl
    delete params.isTempPreviewUrl
    await server.onlineSite(params, function(data){
      let res = {
        data: data,
        params: params,
      };
      commit('onlineSite', res);

      if(isTempPreviewUrl){
        server.getTempPreviewUrl({site_id: params.site_id}, function (data) {
          commit("setTempPreviewUrl", data)
        })
      }
    });
  },
  deleteSite({commit}, params) {
    server.deleteSite(params, function(data){
      let res = {
        data: data,
        params: params,
      };
      commit('deleteSite', res);
    });
  },
  updateSiteData({commit}, params) {
    commit('updateSiteData', params);
  },

  // 数据统计
  getDataAll({commit}, params) {
    server.getDataAll(params, function(data) {
      commit('getDataAll', data.data);
    });
  },
  getNavPrev({commit}, params) {
    server.getNavPrev(params, function(data) {
      if(!params || !params.site_id) {
        commit('setMyNavPrev', data.data);
      }else {
        data.data.site_id = params.site_id;
        commit('setDetailNavPrev', data.data);
      }
    });
  },
  exportDataTotal({commit}, params){
    server.exportDataTotal(params, function(data) {
      commit('setExportDataTotal', {site_id: params.site_id, total: data})
    })
  },
  exportData({commit}, params) {
    server.exportData(params, function() {
      // commit('setExportDataTotal', {site_id: params.site_id, total: data})
    })
  },
  setDetailNavPrev({commit}, params) {
    commit('setDetailNavPrev', params);
  },
  recoverSiteQrcode({commit}, {site_id}){
    server.recoverSiteQrcode({site_id}, function (data) {
      commit("recoverSiteQrcode", data)
    })
  },
  getPromtLists({commit}, params) {
    // 获取 推广标识生成 列表
    server.getPromtLists(params, (data) => {
      commit('setPromtLists', data);
    });
  },
  clearPromtLists({commit}, params) {
    // clear 推广标识生成 列表
    commit('setPromtLists', {});
  },
  addPromt({commit}, params) {
    // 添加 推广链接
    const newParams = {
      site_id: params.site_id,
      stfr: params.stfr,
    };
    server.addPromt(newParams, (data) => {
      if(params.callback) params.callback(data);
    });
  },
  getDictionaryTree({commit}, params) {
    server.getDictionaryTree(params, (data) => {
      if(params.callback) params.callback(data);
    });
  },
  getPromtDay({commit}, params) {
    server.getPromtDay(params, (data) => {
      commit('setPromtDay', data);
    });
  },

  // admin 模版
  handleTurnTemp: ({commit}, params) => {
    // 站点拷贝为模版，需要管理员权限
    const newParams = {
      site_id: params.site_id,
      to: 1,
    };
    server.setTemp(newParams, () => {
      let msg = '操作成功'
      let type = 'success'
      commit("showMessage", {msg, type});
    });
  },
  handleTurnSite: ({commit}, params) => {
    // 模版拷贝为站点
    const newParams = {
      site_id: params.site_id,
      to: 0,
    };
    server.setTemp(newParams, () => {
      let msg = '操作成功'
      let type = 'success'
      commit("showMessage", {msg, type});
    });
  },
  handleGetTempList: ({commit}, params) => {
    // 获取模版列表数据
    const newParams = {
      classfy_id: params.classfy_id,
      keywords: params.keywords,
      status: params.status,
      page: params.page,
      pageSize: params.pageSize,
    };
    server.getTempLists(newParams, (data) => {
      commit('setMyTempLists', data);
      commit('setMyTempListsData', data);
    });
  },
  handleDeleteTemp: ({commit}, params) => {
    // 单个删除模版，只有管理员有权限
    server.deleteSite(params, function(data){
      let res = {
        data: data,
        params: params,
      };
      commit('deleteTemp', res);

      let msg = '操作成功'
      let type = 'success'
      commit("showMessage", {msg, type})
    });
  },
  onlineTemp: ({commit}, params) => {
    let isTempPreviewUrl = params.isTempPreviewUrl
    delete params.isTempPreviewUrl
    server.onlineSite(params, function(data){
      let res = {
        data: data,
        params: params,
      };
      commit('onlineTemp', res);

      if(isTempPreviewUrl){
        server.getTempPreviewUrl({site_id: params.site_id}, function (data) {
          commit("setTempPreviewUrl", data);
        })
      }
    });
  },
  getFormDataTable: ({commit}, params) => {
    server.getFormDataTable(params, (data) => {
      commit('setFormDataTable', data);
    })
  },
  updateFormDataTable: ({commit}, params) => {
    commit('updateFormDataTable', params);
  },
  markFormItem: ({commit}, params) => {
    const index = params.index
    delete params.index
    server.markFormItem(params, (data) => {
      if(data == 1) {
        commit('refreshFormDataTable', {index})
      }
    })
  },
  deleteFormItem: ({commit}, params) => {
    const index = params.index
    delete params.index
    server.deleteFormItem(params, (data) => {
      if(data == 1) {
        commit('refreshFormDataTable', {index})
      }
    })
  },
  getMySite4Data: ({commit}, params) => {
    server.getMySite4Data(params, (data) => {
      commit('setMySite4Data', data);
    });
  },

  // tag
  addTag: ({commit}, params) => {
    server.addTag(params, function(data) {
      if(params.callback) params.callback(data);
    });
  },
  deleteTag: ({commit}, params) => {
    server.deleteTag(params, function(data) {
      if(params.callback) params.callback(data);
    });
  },
  getTaglist: ({commit}, params) => {
    server.getTaglist(params, function(data) {
      commit('setTagAddlist', data.data);
      if(params && params.callback) params.callback(data);
    });
  },
  getSearchTagList: ({commit}, params) => {
    server.getSearchTagList(params, function(data) {
      if(params && params.callback) params.callback(data);
    });
  },
}

// mutations
const mutations = {
  showMessage(state, {msg, type}){
    ElMessage({
      message: msg,
      type: type,
    });
  },
  updataIsDisplayClickStatics(state, {isDisplayClickStatics}){
    state.isDisplayClickStatics = isDisplayClickStatics
  },
  updateClickStatics(state, data){
    let obj = {}
    _.forEach(data, (itemData) => {
      obj[itemData.pos] = itemData
    })
    state.clickStatics = obj
  },
  updateOtherSettingShare(state, data){
    // state.siteData.attrs.share = _.cloneDeep(data);
    _.assign(state.siteData.attrs.share, data);
  },
  setUserInfo (state, data) {
    state.user = data;
  },
  setMediaData (state, data) {
    _.keys(data).forEach((type)=>{
      let arr = data[type].list;
      for(let i = 0; i < arr.length; i++){
        arr[i].isDelete = false;
        arr[i].loading = false;
      }
      if(!state.mediaAllData[type]){
        state.mediaAllData[type] = data[type]
        // Vue.set(state.mediaAllData, type, data[type])
      }else{
        let isResetList
        if(data[type].isResetList){
          isResetList = data[type].isResetList
          delete data[type].isResetList
        }
        _.forEach(data[type], (value, key) => {
          if(key == "list"){
            if(isResetList){
              state.mediaAllData[type][key] = value
            }else{
              let arr = _.concat(state.mediaAllData[type][key], value)
              state.mediaAllData[type][key] = arr
            }
          }else{
            state.mediaAllData[type][key] = value
          }
        })
      }
    });
  },
  deleteMediaList(state, data){
    let arr = [];
    data.items.forEach( id => {
      arr.push({id});
    });
    state.mediaAllData[data.type].list =  _.differenceBy(state.mediaAllData[data.type].list, arr, 'id');
  },
  setMyLists (state, data) {
    state.myLists = data.siteList;
  },
  setMyListsData(state, data) {
    state.myListsData = data;
  },
  addMediaItem (state, data) {
    if(state.mediaAllData[data.type]){
      state.mediaAllData[data.type].list.unshift(data.item);
    }
  },
  updateMediaItem(state, data){
    for(let key in data.item){
      state.mediaAllData[data.type].list[data.index][key] = data.item[key];
    }
  },
  setSiteData(state, data){
    state.siteData = data;
    state.siteDatas[data.id] = data;
  },
  updateSiteData(state, data) {
    state.siteData = data;
  },
  setSitePreview(state, data){
    for(let key in data){
      state.sitePreview[key] = data[key]
    }
  },
  onlineSite(state, res) {
    var siteId = res.params.site_id;
    let myLists = state.myLists;
    myLists.forEach(function(item) {
      if(item.site_id == siteId) {
        item.status = res.params.online;
        return;
      }
    });
  },
  onlineTemp(state, res) {
    var siteId = res.params.site_id;
    let myLists = state.myLists;
    myLists.forEach(function(item) {
      if(item.site_id == siteId) {
        item.status = res.params.online;
        return;
      }
    });
  },
  deleteSite(state, res) {
    var siteId = res.params.site_id;
    let myLists = state.myLists;
    myLists.forEach(function(item, index) {
      if(item.site_id == siteId) {
        myLists.splice(index, 1);
        return;
      }
    });
  },
  setTempPreviewUrl(state, data){
    state.siteTempPreviewItem = data;
  },
  recoverSiteQrcode(state, data){
    //online 2-下线，1-上线
    let qrData = data[state.siteData.id]
    state.siteTempPreviewItem.qrcode = state.siteTempPreviewItem.status == 1 ? qrData.online : qrData.tmp
  },
  setExportDataTotal(state, data){
    state.exportData.total = data.total
    state.exportData.site_id = data.site_id
  },

  // admin 数据统计
  setMyNavPrev(state, data) {
    state.myNavPrev = _.cloneDeep(data);
  },
  setDetailNavPrev(state, data) {
    // TODO: 逻辑有点奇怪？需要整理？
    if(data.isClear) {
      state.detailNavPrev = {};
      return;
    }

    // if(data.site_id) data.time = state.detailNavPrev.time;  // 为什么加在这里？
    state.detailNavPrev = _.cloneDeep(data);
  },
  setPromtLists(state, data) {
    state.myPopularize.popularMarkData = data;
  },
  setMySite4Data(state, data) {
    // set mySite4Data
    state.mySite4Data = _.cloneDeep(data);
    state.mySite4Data.time = data && data.update_time ? data.update_time.split(' ')[0] + ' - 至今' : '至今';
  },
  setPromtDay(state, data) {
    state.myPopularize.popularDayData = _.clone(data);
  },

  // admin 模版
  setMyTempLists(state, data) {
    state.myLists = data.siteList;
  },
  setMyTempListsData(state, data) {
    state.myListsData = data;
  },
  deleteTemp(state, res) {
    var siteId = res.params.site_id;
    let myLists = state.myLists;
    myLists.forEach(function(item, index) {
      if(item.site_id == siteId) {
        myLists.splice(index, 1);
        return;
      }
    });
  },
  setFormDataTable(state, data){
    state.formDataTable = {};
    if(_.isArray(data.columesList)) {
      data.columesList.splice(3, 1)
    }
    state.formDataTable = data;
  },
  updateFormDataTable(state, data) {
    data = data.filter(item => {
      item['is_export'] = '1';
      return item;
    });

    state.formDataTable.siteList = _.merge(state.formDataTable.siteList, data);
  },
  refreshFormDataTable(state, {index}) {
    state.formDataTable.siteList.splice(index, 1);
  },

  // tag
  setTagAddlist(state, data) {
    state.tagAddList = data;
  },
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
